import Vue from 'vue'
import axios from 'axios'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import {
  ACCESS_TOKEN
} from '@/store/mutation-types'
const instance = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: 50000
})
// 异常拦截处理器
const errorHandler = (error) => {
  if (error) {
    console.log('请求发生异常：', error)
  }
}
// 请求拦截
instance.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/json;charset=UTF-8'
  const token = storage.get(ACCESS_TOKEN)
  if (token) {
    config.headers[ACCESS_TOKEN] = token
  }
  return config
}, errorHandler)

// 响应拦截
instance.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

function handleResult (result, callback, errorCallback) {
  if (!result) {
    return
  }
  if (result.code === 1) {
    if (callback) {
      callback(result.data)
    }
  } else if (result.code === 601 || result.code === 602) {
    storage.remove(ACCESS_TOKEN)
    setTimeout(() => {
      window.location.reload()
    }, 0)
  } else {
    if (errorCallback) {
      errorCallback(result)
    }
    notification.error({
      message: '错误',
      description: result.message
    })
  }
}

const request = {
  post (url, params, callback, errorCallback) {
    return instance
      .post(url, params)
      .then(function (result) {
        handleResult(result, callback, errorCallback)
        return result
      })
  },
  get (url, params, callback, errorCallback) {
    return instance
      .get(url, {
        params: params
      })
      .then(function (result) {
        handleResult(result, callback, errorCallback)
        return result
      })
  },
  all (arr, callback) {
    const reqArr = []
    arr.forEach(t => {
      if (t.method === 'get') {
        reqArr.push(instance.get(t.url, {
          params: t.params
        }))
      }
      if (t.method === 'post') {
        reqArr.push(instance.post(t.url, t.params))
      }
    })
    axios.all(reqArr).then(axios.spread((...res) => {
      callback(res)
    }))
  },
  download (url, params, fileName) {
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }
    const token = storage.get(ACCESS_TOKEN)
    if (token) {
      headers[ACCESS_TOKEN] = token
    }
    axios({
      baseURL: process.env.VUE_APP_API_URL,
      method: 'get',
      url: url,
      headers: headers,
      params: params,
      responseType: 'blob'
    }).then((res) => { // 处理返回的文件流
      const content = res.data
      const blob = new Blob([content])
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    })
  },
  downloadMinio (url, fileName) {
    axios({
      method: 'get',
      url: url,
      responseType: 'blob'
    }).then((res) => { // 处理返回的文件流
      const blob = new Blob([res.data])
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    })
  },
  pdfPreview (url, params) {
    axios({
      method: 'get',
      url: url.startsWith('http') ? url : (process.env.VUE_APP_API_URL + url),
      headers: {
        accessToken: localStorage.getItem('accessToken')
      },
      params: params,
      responseType: 'blob'
    }).then((res) => { // 处理返回的文件流
      const blob = new Blob([res.data], { type: 'application/pdf' })
      const pdfUrl = window.URL.createObjectURL(blob)
      window.open(pdfUrl)
    })
  }
}
Vue.prototype.$http = request
export default request
